import * as Constant from '@/constant/index.js';

const toErrorPage = () => {
  uni.navigateTo({ url: '/pages/error/error' });
};

export const navigateTo = (url) => {
  uni.navigateTo({
    url: url,
    fail: (err) => {
      toErrorPage();
    },
  });
};

export const redirectTo = (url) => {
  uni.redirectTo({
    url: url,
    fail: (err) => {
      toErrorPage();
    },
  });
};

export const reLaunch = (url) => {
  uni.reLaunch({
    url: url,
    fail: (err) => {
      toErrorPage();
    },
  });
};

export const switchTab = (url) => {
  uni.switchTab({
    url: url,
    fail: (err) => {
      toErrorPage();
    },
  });
};

export const navigateBack = (delta = 1) => {
  const pages = getCurrentPages();
  const wxlsToken = uni.getStorageSync('wxlsToken') || '';
  let url = '/pages/index/index';
  if (wxlsToken) {
    url = url + '?wxlsToken=' + wxlsToken;
  }
  if (pages.length > 1) {
    uni.navigateBack({
      delta: delta,
      fail: (err) => {
        uni.reLaunch({
          url: url,
        });
      },
    });
  } else {
    uni.reLaunch({
      url: url,
    });
  }
};

// h5 唤起app对应页面首页跳转需要用这个
export const h5uniNavTo = (url) => {
  const link = encodeURIComponent(
    `${
      process.env.NODE_ENV === 'development' ? Constant.DEV_FRONTURL : Constant.PRO_FRONTURL
    }/#${url}`,
  );
  h5uni.navigateTo({
    url: `/pages/webview/index?url=${link}&copyfrom=unlock`,
  });
};
export const h5uniRedTo = (url) => {
  const link = encodeURIComponent(
    `${
      process.env.NODE_ENV === 'development' ? Constant.DEV_FRONTURL : Constant.PRO_FRONTURL
    }/#${url}`,
  );
  h5uni.redirectTo({
    url: `/pages/webview/index?url=${link}&copyfrom=unlock`,
  });
};

export const h5uniNavBack = (url) => {
  h5uni.navigateBack();
};

export const h5uniToAppArticle = (url) => {
  h5uni.navigateTo({
    url: `/pages/shows/index?id=${id}`,
  });
};
